package com.mcy.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.sun.deploy.util.URLUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 在Spring Cloud Gateway中，主要有两种类型的过滤器：GlobalFilter 和 GatewayFilter
 * GlobalFilter ： 全局过滤器，对所有的路由均起作用
 * GatewayFilter ： 只对指定的路由起作用
 *  网关统一验证权限
 *  https://gitee.com/bootstrap2table/ace-security/blob/master/ace-gate/ace-gateway-v2/src/main/java/com/github/wxiaoqi/security/gate/v2/filter/AccessGatewayFilter.java
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Long GLOBAL_LOG_PRIFIX=System.currentTimeMillis();
        HttpHeaders headers= exchange.getRequest().getHeaders();
        System.err.println(headers);
        String token=exchange.getRequest().getHeaders().getFirst("X-AMZ-SECURITY-TOKEN");
        if(StringUtils.isEmpty(token)){
            log.error("用户未登录或无授权");
            /*exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();*/
            return error(exchange,HttpStatus.UNAUTHORIZED,"用户未登录或无授权");
        }
        //模拟生成全局日志编号，添加到header里面
        addHeader(exchange.getRequest().mutate(),"GLOBAL_LOG_PRIFIX",GLOBAL_LOG_PRIFIX);
        System.err.println(headers);
        return  chain.filter(exchange);
    }

    /*值越小越先加载*/
    @Override
    public int getOrder() {
        return -100;
    }

    /**
     * 网关抛异常
     */
    protected Mono<Void> error(ServerWebExchange serverWebExchange,HttpStatus status, String body) {
        serverWebExchange.getResponse().setStatusCode(status);
        Map<String,Object> param= Maps.newHashMap();
        param.put("status",status.value());
        param.put("data",null);
        param.put("msg",body);
        byte[] bytes = JSON.toJSONString(param).getBytes(StandardCharsets.UTF_8);
        serverWebExchange.getResponse().getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        DataBuffer buffer = serverWebExchange.getResponse().bufferFactory().wrap(bytes);
        return serverWebExchange.getResponse().writeWith(Mono.just(buffer));
    }

    /**
     *  网关请求放入数据
     * @param mutate
     * @param name
     * @param value
     */
    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (ObjectUtils.isEmpty(value)) {
            return;
        }
        /*String valueStr = value.toString();
        String valueEncode = URLUtil.encode(valueStr);
        mutate.header(name, valueEncode);*/
        mutate.header(name, value.toString());
    }

}
